package ATM.service.impl;

import ATM.bean.RecordBean;
import ATM.bean.UserBean;
import ATM.dao.IRecordDAO;
import ATM.dao.IUserDAO;
import ATM.dao.impl.RecordDAOImpl;
import ATM.dao.impl.UserDAOImpl;
import ATM.service.UserService;

import java.time.LocalDate;

public class UserServiceImpl implements UserService {
    IUserDAO userDAO = new UserDAOImpl();
    IRecordDAO recordDAO = new RecordDAOImpl();

    /**
     * 登陆
     *
     * @param username 账号
     * @param pwd      密码
     * @return 用户对象，如果登陆失败，返回 null
     */
    @Override
    public UserBean login(String username, String pwd) {
        return userDAO.login(username, pwd);
    }

    /**
     * 存钱，同时添加交易明细
     *
     * @param username 账号
     * @param money    存入金额
     */
    @Override
    public void save(String username, Integer money) {
        UserBean user = userDAO.getUserByName(username);
        //应该用事务提交
        userDAO.update(username, user.getMoney() + money);
        recordDAO.insert(new RecordBean(LocalDate.now(), "存入金额", money, username));
    }

    /**
     * 取钱
     * 1、根据帐号查询用户对象
     * 2、判断用户余额是否超支，如果超支，返回false
     * 3、否则，完成余额减 少
     * 4、添加交易明细
     *
     * @param username 账号
     * @param money    金额
     * @return 取钱是否成功
     */
    @Override
    public boolean get(String username, Integer money) {
        UserBean user = userDAO.getUserByName(username);
        if (money > user.getMoney()) {
            return false;
        }
        userDAO.update(username, user.getMoney() - money);
        recordDAO.insert(new RecordBean(LocalDate.now(), "取出金额", money, username));
        return true;
    }

    /**
     * 查询
     *
     * @param username 账号
     */
    @Override
    public UserBean query(String username) {
        return userDAO.getUserByName(username);
    }

    /**
     * 转账
     * 1、判断转帐帐号是否存在，如果不存在，返回"转帐帐号不存在"
     * 2、判断登陆帐号余额是否充足，如果余额不足，返回“余额不足”
     * 3、登陆帐号减少金额，转帐帐号添加金额
     * 4、登陆帐号添加转出交易记录，转帐帐号添加转入交易记录
     *
     * @param loginUsername 登陆账号
     * @param otherUsername 对方账号
     * @param money         金额
     * @return 转帐失败信息，如果转帐成功，返回null
     * ·
     */
    @Override
    public String trans(String loginUsername, String otherUsername, Integer money) {
        UserBean loginUser = userDAO.getUserByName(loginUsername);
        UserBean otherUser = userDAO.getUserByName(otherUsername);
        String str = "";
        if (otherUser.getUsername() == null) {
            str += "转帐帐号不存在";
            return str;
        }
        if (money > loginUser.getMoney()) {
            str += "余额不足";
            return str;
        }
        //应该用事务提交
        userDAO.update(loginUsername, loginUser.getMoney() - money);
        userDAO.update(otherUsername, otherUser.getMoney() + money);
        recordDAO.insert(new RecordBean(LocalDate.now(), "对" + otherUsername + "账号转出金额", money, loginUsername));
        recordDAO.insert(new RecordBean(LocalDate.now(), loginUsername + "转入金额", money, otherUsername));
        str += "转账成功";
        return str;
    }
}
